package com.zhugang.week13.binarysearch;

/**
 * @program algorithms
 * @description: bSearchFirstGreatherThan
 * @author: chanzhugang
 * @create: 2022/11/25 13:43
 */
public class BinarySearchFirstGreatherThan {

    /**
     * 查找第一个大于等于给定元素的下标, 有重复元素
     * [1,3,5,6,6,8,10]
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bsearch(int[] a, int n, int target) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] >= target) {
                // 向前探测是否是第一个大于等于
                if (mid == 0 || a[mid - 1] < target) {
                    // 前一个元素不满足，则当前mid是第一个大于等于target下标
                    return mid;
                } else {
                    high = mid - 1;
                }
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchFirstGreatherThan binarySearchFirstGreatherThan = new BinarySearchFirstGreatherThan();
        int[] a = {1, 3, 5, 6, 6, 8, 10};
        int index = binarySearchFirstGreatherThan.bsearch(a, a.length, 7);
        System.out.println(index);
    }
}